package com.ygqh.baby.service.task.impl;

import com.alibaba.fastjson.JSON;
import com.ygqh.baby.ao.FileTemplate;
import com.ygqh.baby.ao.FileType;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.TaskMethod;
import com.ygqh.baby.po.YgTaskTime;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.task.YgWdtSkuTaskService;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.DocumentHandler;
import com.ygqh.baby.utils.MailUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * @Author: sunshuo
 * @Date: 2019/8/6/006 15:22
 * @Version: 1.0
 */
@Service
public class YgWdtSkuTaskServiceImpl implements YgWdtSkuTaskService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private YgTaskTimeService ygTaskTimeService;
    @Autowired
    private YgStockService ygStockService;
    @Autowired
    private MailUtil mailUtil;
    @Autowired
    private WdtQybOrderService wdtQybOrderService;
    @Autowired
    private FileService fileService;
    @Value("${image.upload.temp.url}")
    private String tempFileBasePath;

    @Override
    public void syncAllSkuStock() {
        TaskMethod taskMethod = TaskMethod.SyncAllSkuStock;
        logger.info("【{}】开始执行。。。", taskMethod.getTitle());
        Date runTime = new Date();
        YgTaskTime taskTime = ygTaskTimeService.findLastByTaskMethod(taskMethod);
        if (taskTime == null) {
            taskTime = new YgTaskTime();
            taskTime.setMothodName(taskMethod.name());
        }
        taskTime.setRunTime(runTime);
        StringBuilder remark = new StringBuilder("【").append(taskMethod.getTitle()).append("】");
        // 获取所有需要同步库存的SKU编码
        List<String> skuCodeList = ygStockService.getSkuCodeListForSyncStock();
        if (CollectionUtils.isEmpty(skuCodeList)) {
            logger.info("【{}】获取到需要同步库存的SKU编码集合为空", taskMethod.getTitle());
            remark.append("获取到需要同步库存的SKU编码集合为空");
        } else {
            logger.info("【{}】获取到需要同步库存的SKU编码长度：{}", taskMethod.getTitle(), skuCodeList.size());
            remark.append("获取到需要同步库存的SKU编码长度：").append(skuCodeList.size());
            Message message = ygStockService.doSyncStockSplit(skuCodeList, taskMethod.name());
            logger.info("【{}】同步所有SKU库存结果：{}", taskMethod.getTitle(), JSON.toJSONString(message));
            remark.append(", 同步所有SKU库存结果：").append(JSON.toJSONString(message));
            if (!Message.isSuccess(message)) {
                logger.warn("【{}】同步库存结果异常：{}", taskMethod.getTitle(), JSON.toJSONString(message));
                mailUtil.simpleSend("sunshuo@yiigoo.cn", "【" + taskMethod.getTitle() + "】异常", remark.toString());
            }
        }
        taskTime.setRemark(remark.toString());
        ygTaskTimeService.saveOrUpdate(taskTime);
        logger.info("【{}】执行结束！！！", taskMethod.getTitle());
    }

    @Override
    public void sendWDTSalesReportMail() {
        TaskMethod taskMethod = TaskMethod.SendWDTSalesReportMail;
        ygTaskTimeService.execute(taskMethod, taskMethod.getCode(), new YgTaskTimeTemplate() {
            @Override
            public void execute(Date endTime) throws Exception {
                Date startTime = DateConvertUtils.addDay(endTime, -taskMethod.getCode());
                String dateTimeStr =
                        DateConvertUtils.formatDateTime(startTime) + "~" + DateConvertUtils.formatDateTime(endTime);
                logger.info("【{}】 {} 开始执行。。。", taskMethod.getTitle(), dateTimeStr);
                List<Map<String, Object>> dataList = wdtQybOrderService.finSalesReportBySku(startTime, endTime);
                logger.info("【{}】 {} 查询销售数据长度：" + (dataList == null ? 0 : dataList.size()),
                        taskMethod.getTitle(), dateTimeStr);
                File tempFile = createWDTSalesReportExcel(dataList, startTime, endTime);
                if (tempFile != null && tempFile.exists()) {
                    logger.info("【{}】 {} 发送邮件: sunshuo@yiigoo.cn, xiaoshou@yiigoo.com", taskMethod.getTitle(), dateTimeStr);
                    // 发送邮件
                    mailUtil.sendWithAttach(new String[]{"sunshuo@yiigoo.cn", "xiaoshou@yiigoo.com"},
                            "【" + tempFile.getName() + "】", "", Collections.singletonList(tempFile),
                            null);
                    // 业务结束，删除临时文件
                    tempFile.delete();
                }
                logger.info("【{}】 {} 执行结束！！！", taskMethod.getTitle(), dateTimeStr);
            }
        });
    }

    private File createWDTSalesReportExcel(List<Map<String, Object>> dataList, Date startTime, Date endTime) throws Exception {
        if (CollectionUtils.isEmpty(dataList)) {
            return null;
        }
        FileTemplate template = FileTemplate.SkuWDTSalesReport;
        byte[] templateBytes = fileService.downloadFromOss(template.getCode());
        Map<String, Object> dataMap = new HashMap<>(2);
        dataMap.put("resultSet", dataList);
        byte[] bytes = DocumentHandler.createDocument(templateBytes, dataMap);

        String pattern = "MMdd";
        String fileName = String.format(template.getTitle(),
                DateConvertUtils.format(startTime, pattern) + "-" + DateConvertUtils.format(endTime, pattern));
        // 生成到本地临时文件
        File file = new File(tempFileBasePath + fileName);
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(bytes);
            fos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 上传到OSS
        fileService.upload2Oss(FileType.Temp.name() + "/" + fileName, bytes);
        return file;
    }
}
